
#include <QEvent>
#include <QPainter>
#include <QPaintEvent>
#include <QRectF>

#include "fmod.h"
#include "fmod_event.h"

#include "core/engine.h"
#include "ui/button.h"

Button::Button(const QString& rkFilename, QWidget *pkParent)
    : QAbstractButton(pkParent),
      m_bIsHovered(false),
      m_kPixmap(rkFilename)
{
    Q_ASSERT(!m_kPixmap.isNull());

    setAttribute(Qt::WA_Hover);
    setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);

    connect(this, SIGNAL(clicked()), this, SLOT(playSound()));
}

Button::~Button()
{

}

QSize Button::minimumSizeHint() const
{
    return sizeHint() / 2;
}

QSize Button::sizeHint() const
{
    return m_kPixmap.size();
}

bool Button::event(QEvent* pkEvent)
{
    switch(pkEvent->type())
    {
    case QEvent::HoverEnter:
        m_bIsHovered = true;
        update();
        return true;

    case QEvent::HoverLeave:
        m_bIsHovered = false;
        update();
        return true;

    default:
        break;
    }

    return QAbstractButton::event(pkEvent);
}

void Button::paintEvent(QPaintEvent* pkEvent)
{
    // Propagate.
    QWidget::paintEvent(pkEvent);

    // Paint.
    QPainter kPainter(this);

    // TODO : Hover is enabled but no graphics.
    kPainter.drawPixmap(rect(), m_kPixmap, m_kPixmap.rect());
}

void Button::playSound() const
{
    // Play Button clicked sound
    FMOD_RESULT kResult;
    FMOD_EVENT* pkFMODEventButtonClicked;
    kResult = FMOD_EventSystem_GetEvent(Engine::instance().fmod(), "melomaniac/melomaniac/selection", FMOD_EVENT_DEFAULT, &pkFMODEventButtonClicked);
    Q_ASSERT(kResult == FMOD_OK);
    kResult = FMOD_Event_Start(pkFMODEventButtonClicked);
    Q_ASSERT(kResult == FMOD_OK);
}
